package com.linln.admin.pcs.service;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 推送待办事项到中台服务
 */
@Service
public class NotificationMiddleService {
    @Value("${hostInfo.middle}")
    private String middle;
    private final static Logger logger = LoggerFactory.getLogger(NotificationMiddleService.class);


    //推送待办事项数据
    public void send(String content, String targetUrl, Long userId, HttpServletRequest request){
        String serverName = request.getServerName();
        String url = "http://"+serverName+":"+middle+"/api/sys/notification";
        String Authorization ="Fv340FP60umod0YctyaFRsFfxLy3eMTA";
        //发起网络请求,post请求推送数据
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Authorization", Authorization);
        // 构建请求体
        Map<String, Object> body = new HashMap<>();
        body.put("content", content);
        body.put("userId", userId);
        body.put("targetUrl", targetUrl);

        // 发送 POST 请求
        RestTemplate restTemplate = new RestTemplate();
        try {
            ResponseEntity<String> response = restTemplate.postForEntity(
                    url,
                    new HttpEntity<>(body, headers),
                    String.class
            );

            // 可选：处理响应
            if (!response.getStatusCode().is2xxSuccessful()) {
                // 记录请求失败日志
                logger.error("推送中台失败，状态码：{}，响应内容：{}",
                        response.getStatusCodeValue(),
                        response.getBody());
            }
        } catch (RestClientException e) {
            // 处理网络异常
            logger.error("推送中台请求异常：", e);
        }

    }
}
